var DataGrid = function(json){
    var name = 'dataGrid -- edit by Ray';
    this.$host = window.location.protocol + '//' + window.location.host;
    this.$projectName = '/acct-monitor/acct/v1/monitor';
    this.path = this.$host + this.$projectName;
    //this.path = 'http://localhost:8082/acct-monitor/acct/v1/monitor/';
    this.rows = json.rows || 10;
    this.gridId = json.gridId || 'dataGrid';
    this.pageId = json.pageId || 'pager';
    this.area = json.size ?[json['size'][0] + 'px',json['size'][1] + 'px']:['880px','600px'];
    this.searchFromId = json.searchFromId || 'searchFrom';
    this.editFromId = json.editFromId || 'editFrom';
    this.listUrl = json.listUrl;
    this.addUrl = json.addUrl && json.addUrl;
    this.editUrl = json.listUrl && json.listUrl;
    this.delUrl = json.listUrl && json.listUrl;
    this.tempo = json.gridId && Tempo.prepare(this.gridId);
    this.formatCode = json.formatCode || [];
    this.formatData = json.formatData || [];
}
//封装$.ajax方法
DataGrid.prototype.$ajax = function(json){
    var self = this;
    if(!json.url){
        console.log('#################################请求的URL参数必须配置，不能为空！');
        return false;
    }
    $.ajax({
        type:json.type?json.type:'POST',
        data:json.data&&JSON.stringify(json.data),
        url:self.path + json.url,
        dateType:'json',
        contentType:json.contentType?json.contentType:'application/json',
        async:json.async?json.async:false,
        timeout:5000,
        success:function(data){
            if(data.respBody){
                var result = data.respBody;
                json.callback && json.callback(result);
            }else{
                layer.alert(
                    '错误码：'+ data['respHeader']['resultCode']+'</br>错误信息：'+data['respHeader']['resultDesc'],
                    {icon:0}
                );
            }
        },
        error:function(x,t,e){
            layer.alert('网络故障！',{icon:5});
            $('#'+self.gridId).hide();
        }
    })
}

/*生成表格
postData:
unPager:
*/
DataGrid.prototype.createDataGrid = function(json){
    var self = this,
        url = '';
    if(json.unPager){
        url = json.postData?
            self.listUrl + '?' + self.handleParamForGet(json.postData):
            self.listUrl
    }else{
        url = json.postData?
            self.listUrl + '?' + self.handleParamForGet(json.postData) + '&page=1&row=' + self.rows:
            self.listUrl+ '&page=1&row=' + self.rows
    }
    self.$ajax({
        url:url,
        type:'GET',
        callback:function(data){
            var result = data['list'] || [];
            self.formatDataFn(result);
            self.tempo.render(result);
            !json.unPager && self.pagination(data)
        }
    });
}
/*原始数据值转义方法*/
DataGrid.prototype.formatDataFn = function(result){
    var self = this;
    if(result.length>0 && self.formatCode.length>0 && self.formatData.length>0){
        for(var i=0;i<result.length;i++){
            for(var j=0;j<self.formatCode;j++){
                for(var key in self.formatData[j]){
                    if(String(result[i][self.formatCode[j]])==key) result[i][self.formatCode[j]]=self.formatData[j][key];
                }
            }
        }
    }
}
/*封装分页功能
参数：data:
*/
DataGrid.prototype.pagination = function(data){
    var self = this,
    pageStr = '<ul><li class="page-No-box" id="pageNoBox">'+
                '<i class = "fa fa-backward" id = "backward"></i>'+
                '<input type = "text" id = "pager-pageNo" class= "page-No-input">'+
                '<i class = "fa fa-forward" id = "forward"></i><li>'+
                '<li class = "pager-total-box">总记录：<em>'+data['total']+'</em>条/'+
                '总页数：<em>'+data['pages']+'</em>页</li></ul>';
    $('#'+self.pageId).html(pageStr);
    $('#pager-pageNo').val(data['pageNum']);
    var pageNo = Number($('#pager-pageNo').val());
    /*减页码*/
    $('#backward').click(function(){
        if(pageNo >1 ){
            pageNo -=1;
            $('#pager-pageNo').val(pageNo);
            self.reloadGridData(pageNo);
        }
    });
    /*加页码*/
        $('#forward').click(function(){
            if(pageNo < data['pages'] ){
                pageNo +=1;
                $('#pager-pageNo').val(pageNo);
                self.reloadGridData(pageNo);
            }
        });
    /*监听手动输入页码方法*/
    $('#pager-pageNo').change(function(){
        if(pageNo >= 1 && pageNo<=data['pages']){
            self.reloadGridData(pageNo);
        }
    });
}
/*重新加载表格数据*/
DataGrid.prototype.reloadGridData = function(pageNo){
    var self = this;
    self.$ajax({
        url:self.listUrl + '>page='+pageNo+'&rows='+self.rows,
        type:'GET',
        callback:function(data){
            var result = data['list'] || [];
            self.formatDataFn(result);
            self.tempo.render(result);
            self.pagination(data)
        }
    });
}
/*搜索表格数据*/
DataGrid.prototype.searchDataGrid = function(params){
    var self = this;
    if(typeof(params) != undefined)
    self.$ajax({
        url:self.listUrl + '?page=1&rows='+self.rows + '&' + self.handleParamForGet(params),
        type:'GET',
        callback:function(data){
        var result = data['list'] || [];
        self.formatDataFn(result);
        self.tempo.render(result);
        self.pagination(data)
        }
    });
}
/*新增数据*/
DataGrid.prototype.addRowData = function(json){
    var self = this,
        tpl = json.tplId?$('#'+json.tplId).html():$('template').html(),
        index,
        formatData;
    index = layer.open({
        type:1,
        title:json.title || '新增信息',
        content:tpl,
        skin:'layui-layer-demo',
        anim:0,
        area:self.area,
        btn:['提交','取消'],
        btn1:function(){
            formatData = $("#"+self.editFromId).formToJson()
            var postData = json.otherData>self.mergeJson(formData,otherData):formData;
            if($('#'+self.editFromId).formValidate()){
                self.$ajax({
                    url:self.addUrl,
                    data:postData,
                    callback:function(){
                        layer.msg('新增数据成功！',{time:2500,offset:'t'});
                        layer.close(index);
                        self.reloadGridData(1);
                    }
                })
            }
        }
    });
    json.callback && json.callback();
}
/*编辑行内数据
参数：
    elem:this,
    json:
        unEditField
        formatCode
        formData
        title
        tplId
        callback
        editBack
*/
DataGrid.prototype.editRowData = function(elem,json){
    var self = this,
        currOper = $(elem).attr('role'),
        rowData = self.getRowData(elem),
        unEditField = json.unEditField?json.unEditField : [],
        formatCode = json.formatCode?json.formatCode :[],
        formatData = json.formatData?json.formatData :[].
        index;
    if(currOper == 'edit'){
        self.formatCommonCode(formatCode,formatData,rowData);
        index = layer.open({
            type:1,
            anim:0,
            title:json.title?json.title:'编辑信息',
            area:self.area,
            content:json.tplId?json.tplId:$('template').html(),
            btn:['提交','取消'],
            btn1:function(){
                $('#'+self.editFromId + 'select').removeAttr('disabled');
                var formatData = $('#'+self.editFromId).formToJson();
                postData = json.otherData?self.mergeJson(json.otherData,formData):formData,
                key = formData[json['key']];
                if($('#'+self.editFromId).formValidate()){
                    self.$ajax({
                        url:self.editUrl + '/' +key,
                        data:postData,
                        type:'put',
                        callback:function(data){
                            layer.msg('修改信息成功！',{time:2500,offset:'t'});
                            layer.close(index);
                            self.reloadGridData(1);
                        }
                    })
                }
            },
            btn2:function(){layer.closeAll()}
        });
        //////*暂停*///
    }
}